window.downloadFile = function (sUrl) {

    //iOS devices do not support downloading. We have to inform user about this.
    if (/(iP)/g.test(navigator.userAgent)) {
        alert('Your device does not support files downloading. Please try again in desktop browser.');
        return false;
    }

    //If in Chrome or Safari - download via virtual link click
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined) {
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
            link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
            var e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            link.dispatchEvent(e);
            return true;
        }
    }

    // Force file download (whether supported by server).
    if (sUrl.indexOf('?') === -1) {
        sUrl += '?download';
    }

    window.open(sUrl, '_self');
    return true;
}

window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

/**
 * 公共方法类
 *
 * 使用  变量名=function()定义函数时，如果在变量名前加var，则这个变量变成局部变量
 */
var Common = function () {
    /*
     * 获取url参数
     */
    var getQueryStr = function (sUrlParam, sArgName) {
        var retval = "";
        if (sUrlParam == null || sUrlParam.length == 0) {
            return retval;
        }
        var args = sUrlParam.split("&");
        for (var i = 0; i < args.length; i++) {
            sUrlParam = args[i];
            var arg = sUrlParam.split("=");
            if (arg.length <= 1)
                continue;
            if (arg[0] == sArgName)
                retval = arg[1];
        }
        return retval;
    }

    /*
     * ajax发送post请求
     */
    var postReq = function (url, param, fnCallback, isIndex) {
        var target, options = {
            title: "异常信息",
            content: "",
            bodyType: "errorMessage"
        };

        if (isIndex) {
            target = window;
        }
        else {
            target = window.parent;
        }

        $.ajax({
            url: url,
            type: "POST",
            timeout: 300000,
            headers: "Access-Control-Allow-Origin:*",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            dataType: "json",
            data: param
        }).done(function (data, textStatus, jqXHR) {
            if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
                options.content = '会话已经超时.';
                target.showModal(options, function () {
                    target.location.href = 'login.html';
                });
            }
            else if (!data) {
                options.content = '无返回信息.';
                target.showModal(options, function () {
                    // donothing
                });
            }
            else {
                fnCallback(data);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 0) {
                options.content = '请求异常，网络连接失败！';
            }
            else if (jqXHR.status == 403) {
                options.content = jqXHR.responseJSON.message;
            }
            else {
                options.content = "请求异常，状态码：" + jqXHR.status;
            }

            target.showModal(options, function () {
                // donothing
            });
        });
    };

    var postReq = function (url, param, fnCallback, isIndex) {
        var target, options = {
            title: "异常信息",
            content: "",
            bodyType: "errorMessage"
        };

        if (isIndex) {
            target = window;
        }
        else {
            target = window.parent;
        }

        $.ajax({
            url: url,
            type: "POST",
            timeout: 300000,
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            dataType: "json",
            data: param
        }).done(function (data, textStatus, jqXHR) {
            if (jqXHR.getResponseHeader('sessionStatus') == 'timeout') {
                options.content = '会话已经超时.';
                target.showModal(options, function () {
                    target.location.href = 'login.html';
                });
            }
            else if (!data) {
                options.content = '无返回信息.';
                target.showModal(options, function () {
                    // donothing
                });
            }
            else {
                fnCallback(data);
            }
        }).fail(function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status == 0) {
                options.content = '请求异常，网络连接失败！';
            }
            else if (jqXHR.status == 403) {
                options.content = jqXHR.responseJSON.message;
            }
            else {
                options.content = "请求异常，状态码：" + jqXHR.status;
            }

            target.showModal(options, function () {
                // donothing
            });
        });
    };

    return {
        getQueryStr: getQueryStr,
        postReq: postReq
    }
}();

/*Common.postReq('svcinfo/findForSelect.do', {
    svcAlias: key
}, function (json) {
    if ($.trim(key) == '') {
        // splice(a1,a2,a3...)从a1位置开始替换a2个元素为a3...
        json.data.splice(0, 0, {
            svnName: 'all',
            svcAlias: '所有服务'
        });
    }
    me.cacheDataSource = [];//清空原数组，避免内存泄露
    me.cacheDataSource[key] = json.data;
    query.callback({
        results: json.data
    });
});*/



/**
 * 文件的大小换算
 * @param limit
 * @returns {string}
 */
window.getfileSize = function(limit) {
    var size = "";
    if(limit == 0)
        return "0B";
    if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
        size = limit.toFixed(2) + "B";
    } else if (limit < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + "KB";
    } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB";
    } else { //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
    }

    var sizestr = size + "";
    var len = sizestr.indexOf("\.");
    var dec = sizestr.substr(len + 1, 2);
    if (dec == "00") {//当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
    }

    return sizestr;
}
